package com.tim.app.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.smarttab.SmartTabLayout;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.logic.UserManager;
import com.tim.app.ui.adapter.TabAdapter;
import com.tim.app.ui.fragment.search.SearchArticleContainerFragment;
import com.tim.app.ui.fragment.search.SearchProblemContainerFragment;
import com.tim.app.ui.fragment.search.SearchTopicContainerFragment;
import com.tim.app.ui.fragment.search.SearchUserContainerFragment;
import com.tim.app.util.SoftKeyboardUtil;


/**
 * 搜索页面
 */
public class SearchActivity extends BaseActivity {

    public static final String TAG = "SearchActivity";
    public static final int SEARCH_ALL = 1;//首页
    public static final int SEARCH_USER = 2;//用户
    public static final int SEARCH_SUNJECT = 3;//话题


    private ImageButton ibDelete;
    private EditText etSearch;
    private TextView tvCancel;
    private int searchFrom = SEARCH_ALL;
    private String content;

    private SmartTabLayout tab_layout;
    private ViewPager vpSearchResult;
    private TabAdapter pagerAdapter;

    Handler mHandler;
    SearchTask mSearchTesk;

    public static void start(Context context, int type, String content) {
        Intent intent = new Intent(context, SearchActivity.class);
        intent.putExtra(AppKey.SEARCH_FROM, type);
        intent.putExtra(AppKey.SEARCH_CONTENT, content);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    public void initView() {
        ibDelete = (ImageButton) findViewById(R.id.ibDelete);
        etSearch = (EditText) findViewById(R.id.etSearch);
        tvCancel = (TextView) findViewById(R.id.tvCancel);

        tab_layout = (SmartTabLayout) findViewById(R.id.tab_layout);
        vpSearchResult = (ViewPager) findViewById(R.id.vpSearchResult);

        ibDelete.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (actionId) {
                    case EditorInfo.IME_ACTION_SEARCH:
                        String keyWords = etSearch.getText().toString().trim();
                        doSearch(keyWords, AppKey.SEARCH_TYPE_ALL, true);
                        break;
                }
                return true;
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!TextUtils.isEmpty(etSearch.getText().toString())) {
                    ibDelete.setVisibility(View.VISIBLE);
                } else {
                    ibDelete.setVisibility(View.GONE);
                }
                mHandler.removeCallbacks(mSearchTesk);
                mHandler.postDelayed(mSearchTesk, 500);
            }
        });
        searchFrom = getIntent().getIntExtra(AppKey.SEARCH_FROM, SEARCH_ALL);
        content = getIntent().getStringExtra(AppKey.SEARCH_CONTENT);

        pagerAdapter = new TabAdapter(getSupportFragmentManager());

//        pagerAdapter.addFragment(new SearchAllContainerFragment(), getString(R.string.search_result_tab_title_1));
//        pagerAdapter.addFragment(new SearchAnswerContainerFragment(), getString(R.string.search_result_tab_title_1));
        pagerAdapter.addFragment(new SearchProblemContainerFragment(), getString(R.string.search_result_tab_title_1));
        pagerAdapter.addFragment(new SearchUserContainerFragment(), getString(R.string.search_result_tab_title_2));
        pagerAdapter.addFragment(new SearchTopicContainerFragment(), getString(R.string.search_result_tab_title_3));
        pagerAdapter.addFragment(new SearchArticleContainerFragment(), getString(R.string.search_result_tab_title_4));
        vpSearchResult.setOffscreenPageLimit(3);
        vpSearchResult.setAdapter(pagerAdapter);
        vpSearchResult.setCurrentItem(0);
        tab_layout.setViewPager(vpSearchResult);
        switch (searchFrom) {
            case SEARCH_ALL:
                vpSearchResult.setCurrentItem(0);
                doSearch(content, AppKey.SEARCH_TYPE_ALL, true);
                break;
            case SEARCH_USER:
                vpSearchResult.setCurrentItem(1);
                doSearch(content, AppKey.SEARCH_TYPE_USER, true);
                break;
            case SEARCH_SUNJECT:
                vpSearchResult.setCurrentItem(2);
                doSearch(content, AppKey.SEARCH_TYPE_SUBJECT, true);
                break;
        }
        mHandler = new Handler();
        mSearchTesk = new SearchTask();

        etSearch.requestFocus();
        SoftKeyboardUtil.showSoftKeyboard(etSearch);

        EventManager.ins().registListener(EventTag.DO_SEARCH_JUMP, eventListener);
        EventManager.ins().registListener(EventTag.DO_SEARCH_BY_HISTORY, eventListener);
    }

    /**
     * 搜索任务
     */
    class SearchTask implements Runnable {

        @Override
        public void run() {
            if (!TextUtils.isEmpty(etSearch.getText().toString())) {
                doSearch(etSearch.getText().toString(), AppKey.SEARCH_TYPE_ALL, false);
            } else {
                EventManager.ins().sendEvent(EventTag.DO_SHOW_SEARCH_RECOMMAND, 0, 0, null);
            }
        }
    }

    /**
     * 模拟搜索
     *
     * @param keyWord
     */
    private void doSearch(String keyWord, int type, boolean isAddToHistory) {
        if (TextUtils.isEmpty(keyWord))
            return;
        if (isAddToHistory) {
            etSearch.setText(keyWord);
        }
        etSearch.setSelection(keyWord.length());
        etSearch.clearFocus();
        if (isAddToHistory) {
            UserManager.ins().addSearchHistory(keyWord);
            EventManager.ins().sendEvent(EventTag.DO_ADD_SEARCH_HISTORY, 0, 0, null);
        }
        EventManager.ins().sendEvent(EventTag.DO_SEARCH, 0, 0, keyWord);
    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibDelete:
                etSearch.setText("");
                ibDelete.setVisibility(View.GONE);
                break;
            case R.id.tvCancel:
                SoftKeyboardUtil.hideSoftKeyboard(etSearch);
                addToHistory();
                finish();
                break;
        }
    }

    private void addToHistory() {
        if (!TextUtils.isEmpty(etSearch.getText().toString())) {
            UserManager.ins().addSearchHistory(etSearch.getText().toString());
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        addToHistory();
    }

    private EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, final Object dataobj) {
            if (what == EventTag.DO_SEARCH_JUMP) {
                int type = (int) dataobj;
                switch (type) {
                    case SEARCH_USER:
                        vpSearchResult.setCurrentItem(1);
                        break;
                    case SEARCH_SUNJECT:
                        vpSearchResult.setCurrentItem(2);
                        break;
                }
            } else if (what == EventTag.DO_SEARCH_BY_HISTORY) {
                doSearch(String.valueOf(dataobj), SEARCH_ALL, true);
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.DO_SEARCH_JUMP, eventListener);
        EventManager.ins().removeListener(EventTag.DO_SEARCH_BY_HISTORY, eventListener);
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

}
